<template>
	<view class="container">
		<view class="item flex-row" @tap="changeConversation(item)" v-for="item in list" :key="item.conversationId">
			<view class="">
				<xbc-avatar class="avatar" :src="item.profile.avatar" :group="item.type == 'group'" />
				<xbc-badge :count="item.unreadCount" />
			</view>
			<view class="info">
				<view class="flex-row">
					<view class="name">{{ item.profile.name }}</view>
					<view class="time">{{ item.lastMessage.createdAt }}</view>
				</view>
				<view class="message text-ellipsis">{{ item.lastMessage.contentText }}</view>
			</view>
		</view>
	</view>
</template>

<script>
import XBCIM from 'xbcim'
export default{
	data(){
		return {
			list: []
		}
	},
	onShow(){
		this.getList()
		this.getUnreadCount()
		
		// 监听会话列表更新
		XBCIM.on(XBCIM.EVENT.CONVERSATION_LIST_UPDATE, this.getList)
	},
	onHide(){
		// 取消监听会话列表更新
		XBCIM.off(XBCIM.EVENT.CONVERSATION_LIST_UPDATE, this.getList)
	},
	onLoad(){
		// 监听收到消息
		XBCIM.on(XBCIM.EVENT.MESSAGE_RECEIVED, this.getUnreadCount)
	},
	methods: {
		// 获取会话列表
		async getList() {
			this.list = await XBCIM.getConversationList()
		},
		// 获取会话未读数
		async getUnreadCount() {
			const unreadCount = await XBCIM.getConversationUnreadCount()
			if (unreadCount > 0) {
				uni.setTabBarBadge({
					index: 0,
					text: unreadCount.toString()
				})
			} else {
				uni.removeTabBarBadge({
					index: 0
				})
			}
		},
		// 切换会话
		changeConversation(conversation) {
			const { type, conversationId } = conversation
			uni.setStorageSync('currentConversation', conversation)
			uni.navigateTo({
				url: `/pages/chat/${type}?id=${conversationId}`
			})
		}
	}
}
</script>

<style lang="scss" scoped>
.item {
	padding: 30rpx;
	justify-content: flex-start;
	border-bottom: 2rpx solid #f5f5f5;
	position: relative;

	.info {
		width: calc(100% - 120rpx);
		margin-left: 30rpx;

		.name {
			color: #333;
			font-size: 32rpx;
		}

		.time {
			color: #999;
			font-size: 28rpx;
		}

		.message {
			color: #666;
			font-size: 26rpx;
			margin-top: 12rpx;
		}
	}
}
</style>